

package mesh

import (
	"fmt"
	"cgs-server/helper"
	"cgs-server/server"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"net/http"
)

func init() {
	//server.Handle(http.MethodPost, "/api/Mesh/Download", Download, server.ListMesh)
	server.Post("/api/Mesh/Download", Download, "下载模型文件", server.Login)
}

// Download download a mesh.
func Download(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	id, err := primitive.ObjectIDFromHex(r.FormValue("ID"))
	if err != nil {
		helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  "ID is not allowed.",
		})
		return
	}

	db, err := server.Mongo()
	if err != nil {
		helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  err.Error(),
		})
		return
	}

	filter := bson.M{
		"_id": id,
	}

	mesh := Model{}
	find, _ := db.FindOne(server.MeshCollectionName, filter, &mesh)

	if !find {
		helper.WriteJSON(w, server.Result{
			Code: 300,
			Msg:  "The asset is not existed!",
		})
		return
	}

	// create zip file
	//savePath := server.MapPath(doc["SavePath"].(string))
	//
	//now := helper.TimeToString(time.Now(), "yyyyMMddHHmmssfff")
	//destFile := fmt.Sprintf("/temp/%v.zip", now)
	//descPhysicalFile := server.MapPath(destFile)
	//
	//helper.Zip(savePath, descPhysicalFile)

	result := Result{}
	result.Code = 200
	result.Msg = "Download successfully!"
	result.Path = fmt.Sprintf("%v/temp/%v", mesh.SavePath, mesh.SaveName)
	_, _ = helper.WriteJSON(w, result)
}

// Result means a download mesh result.
type Result struct {
	server.Result
	Path string
}
